var YAHOO={Finance:{SymbolSuggest:{}}};

jQuery(document).ready(function($) {	
	$.each(tagsuggest.tags, function (i, tag) {
		$("#setags-editor-before").append(getAddedTagHTML(tag));
	});
	
	$("#setags-editor-input").bind ("keyup", function(event) {
		var query = $("#setags-editor-input").val();
		if (query.length>0) {
			
	       $.ajax({
	              type: "GET",
	              url: "http://d.yimg.com/autoc.finance.yahoo.com/autoc",
	              data: {query: query},
	              dataType: "jsonp",
	              jsonp : "callback",
	              jsonpCallback: "YAHOO.Finance.SymbolSuggest.ssCallback",
	        });	
		}

		YAHOO.Finance.SymbolSuggest.ssCallback = function (data) {
			if (! $.isEmptyObject(data)) {			
				var tagsHTML = "";
				$.each (data.ResultSet.Result, function(i, stock) {
					tagsHTML += getSuggestedTagHTML (stock.symbol, stock.name);
				});		
				$("#setags-suggest").html(tagsHTML);
				$("#setags-suggest").show();
			} else {
				$("#setags-suggest").hide();
			}
	    }		
	});	
	
	$("body").on("click", ".suggestedtag", function() {
		$("#setags-editor-before").append(getAddedTagHTML($(this).children(".name").text()));
		$("#setags-suggest").html("");
		$("#setags-suggest").hide();
		$("#setags-editor-input").val("");
	})
	$("body").on("click", ".deleteTag", function() {
		$(this).parent().remove();
	})	
	
});

function getSuggestedTagHTML (name, description) {
	var tagsHTML = '<div class="suggestedtag">';
	tagsHTML += '<span class="name">' + name + '</span>';
	tagsHTML += '<span class="description">' + description + '</span>';
	tagsHTML += '</div>';
	return tagsHTML;
}
function getAddedTagHTML (name) {
	return '<span class="addedTag">' + name + '<span class="deleteTag" title="remove this tag"> x </span><input type="hidden" name="setags[]" value="' + name + '"></span>';
}
